<?php
namespace App\Services;

use App\Helpers\Api\MiniProgramTrait;

class SafeCheckService {
    use MiniProgramTrait;

    public static function handle($input) {
        $self = new self();
        $hit = false;
        $hit_url = '';
        $app = $self->miniProgram();
        if ($input['type'] == 'file') {
            $arr = json_decode($input['content'], true);
            foreach ($arr as $item) {
                $origin_url = $item . '?imageView2/1/w/150';
                $url = $self->downloadImage($origin_url);
                $result = $app->content_security->checkImage($url);
                unlink($url);
                $predicts = $result['errcode'];
                if ($predicts != 0) {
                    $hit_url = $item;
                    $hit = true;
                    break;
                }
            }
            return ['hit' => $hit, 'hit_url' => $hit_url];
        }
        else {
            $result = $app->content_security->checkText($input['content']);
            $predicts = $result['errcode'];
            $hit = false;
            if ($predicts != 0)
                $hit = true;

            return $hit;
        }
    }

    private function downloadImage($url)
    {
        $path = public_path('./images/');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = time() . rand(0, 10000) . rand(10000, 100000);
        $extendsion = pathinfo($url, PATHINFO_EXTENSION) ?: 'jpg';
        $filename .= "." . $extendsion;
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $path . $filename;
    }

}